﻿using System;
using System.Web;
using System.Web.Caching;

namespace NTQOnlineExam.Services.Infrastructure
{
    internal class WebCacheStrategy : ICacheStrategy
    {
        private static bool IsEnabled
        {
            get { return true; }
        }

        public object Get(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            }
            return IsEnabled ? HttpRuntime.Cache.Get(key) : null;
        }

        public T Get<T>(string cacheKey, int seconds, Func<T> func)
        {
            // the func is null so we return null
            if (func == null)
            {
                return default(T);
            }
            // the cachekey is empty so we return the result of calling func
            if (string.IsNullOrEmpty(cacheKey))
            {
                return func();
            }

            // we try to retrieve the result from the cache
            var cachedObject = Get(cacheKey);
            if (cachedObject != null)
            {
                return (T)cachedObject;
            }

            // the result is returned from func an inserted into cache if it is enabled
            T result = func();
            if (IsEnabled)
            {
                Insert(cacheKey, result, seconds);
            }
            return result;
        }


        public void Insert(string key, object obj, int seconds)
        {
            if (!string.IsNullOrEmpty(key) && (obj != null) && IsEnabled)
            {
                HttpRuntime.Cache.Insert(key, obj, null, DateTime.Now.AddSeconds(seconds), TimeSpan.Zero, CacheItemPriority.Normal, null);
            }
        }

        public void Max(string key, object obj)
        {
            if (!string.IsNullOrEmpty(key) && (obj != null) && IsEnabled)
            {
                HttpRuntime.Cache.Insert(key, obj, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
            }
        }

        public void Remove(string key)
        {
            if (!string.IsNullOrEmpty(key) && IsEnabled)
            {
                HttpRuntime.Cache.Remove(key);
            }
        }

        public void Clear()
        {
            var e = HttpRuntime.Cache.GetEnumerator();
            while (e.MoveNext())
            {
                HttpRuntime.Cache.Remove(e.Key.ToString());
            }
        }
    }
}
